import React from "react";
import SearchHeader from "./component/SearchHeader";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import "../style/style.less";
import ThePagination from "../../../components/ThePagination";
import { apiUpdateInventory } from '@/request/commodity'
import { apiGetRoomInfoList, apiUpdateRoomInfo } from '@/request/house'

import TheDialog from '@/components/TheDialog'
import { exportSheetTable } from '@/utils/exportTable'
import Add from './component/Add';
import { Tag } from "antd";

class List extends React.Component {
    state = {
        verificationPersonnelId: '',
        columns: [
            {
                title: "房型名称",
                dataIndex: "serviceName",
                key: "serviceName",
            },
            {
                title: "房号",
                dataIndex: "roomName",
                key: "roomName",
            },
            {
                title: "排序",
                dataIndex: "sort",
                key: "sort",
            },
            {
                title: "备注",
                dataIndex: "remark",
                key: "remark",
            },
            {
                title: "状态",
                dataIndex: "useStatus",
                key: "useStatus",
                render: (text, render) => {
                    return (
                        <div>
                            {render.useStatus === 'Y' && <Tag>上架</Tag>}
                            {render.useStatus === 'N' && <Tag>下架</Tag>}
                        </div>
                    )
                }
            },
            {
                title: "操作",
                fixed: "right",
                width: 200,
                render: (text, render) => {
                    return (
                        <div>
                            {render.useStatus === 'Y' && <TheButton hasPermi={['house:number:putShelf']} onClick={() => this.putShelf(render.roomId, 'N')}>下架</TheButton>}
                            {render.useStatus === 'N' && <TheButton hasPermi={['house:number:offShelf']} onClick={() => this.offShelf(render.roomId, 'Y')}>上架</TheButton>}
                            <TheButton hasPermi={['house:number:edit']} onClick={() => this.goEdit('edit', render.roomId)}>编辑</TheButton>
                            <TheButton hasPermi={['house:number:delete']} onClick={() => this.delConfirm(render.roomId)}>删除</TheButton>
                        </div>
                    );
                },
            },
        ],
        dataSource: [],
        pageData: {
            pageNo: 1,
            pageSize: 10,
        },
        type: '',
        total: 0,
        visible: false,
        searchValue: {},
        loading: false
    };
    async componentDidMount() {
        if (localStorage.getItem('searchValue') && localStorage.getItem('pageNo')) {
            let search = JSON.parse(localStorage.getItem('searchValue'))
            this.setState({
                searchValue: search,
                pageData: {
                    pageNo: localStorage.getItem('pageNo'),
                    pageSize: 10
                }
            }, async () => {
                await this.getData()
            })
        } else if (localStorage.getItem('pageNo')) {
            this.setState({
                pageData: {
                    pageNo: localStorage.getItem('pageNo'),
                    pageSize: 10
                }
            }, async () => {
                await this.getData()
            })
        } else {
            await this.getData()
        }
    }
    getData = async () => {
        this.setState({ loading: true })
        const { pageData, searchValue } = this.state
        let res = await apiGetRoomInfoList({ ...pageData, ...searchValue })
        if (res.code === 0 && res.data) {
            this.setState({ dataSource: res.data, pageData: { pageNo: res.pageNo, pageSize: res.pageSize }, total: res.totalCount, loading: false })
        }
    }
    getValue = (value) => {
        this.setState({
            searchValue: value,
            pageData: {
                pageNo: 1,
                pageSize: 10
            }
        }, () => {
            this.getData()
            let search = JSON.stringify(this.state.searchValue)
            localStorage.setItem('searchValue', search)
            localStorage.setItem('pageNo', this.state.pageData.pageNo)
        })
    }
    goDetail = (productId) => {
        this.props.history.push(`/commodity/list/detail/${productId}`);
    };
    goEvaluate = (productId, storeName) => {
        this.props.history.push(`/commodity/list/evaluate/${productId}/${encodeURIComponent(storeName)}`);
    };

    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => {
            localStorage.setItem('pageNo', this.state.pageData.pageNo);
            this.getData()
        })
    };
    delConfirm = (productId) => {
        React.$confirm({
            title: "您确认删除此条商品吗?",
            onOk: async () => {
                await React.$delete('/management/roomInfo/' + productId).then(res => {
                    if (res.code === 0) {
                        React.$message({
                            type: 'info',
                            content: '删除成功'
                        })
                        let { pageNo, pageSize } = this.state.pageData
                        let { total } = this.state
                        this.getData()
                    }
                })
                // let res = await apiProductInfoDel({ productId })
                // if (res.code === 0) {
                //     React.$message({
                //         type: 'info',
                //         content: '删除成功'
                //     })
                //     this.getData()
                // }
            },
        });
    };
    offShelf = (roomId, useStatus) => {
        React.$confirm({
            title: '您确定上架该商品吗？',
            onOk: async () => {
                await apiUpdateRoomInfo({ roomId, useStatus })
                await this.getData()
            }
        })
    }
    putShelf = (roomId, useStatus) => {
        React.$confirm({
            title: '您确定下架该商品吗？',
            onOk: async () => {
                await apiUpdateRoomInfo({ roomId, useStatus })
                await this.getData()
            }
        })
    }
    openSkuDialog = (skuProductId) => {
        this.setState({
            skuVisible: true,
            skuProductId
        })
    }
    closeSkuDialog = () => {
        this.setState({
            skuVisible: false,
            skuProductId: ''
        })
    }
    getSkuProperty = (skuPropertyArray, skuPropertyTable, skuType) => {
        let arr = [];
        if (skuPropertyTable.length > 0) {
            if (
                Object.prototype.toString.call(skuPropertyTable[0]) ===
                "[object Object]"
            ) {
                skuPropertyTable.forEach((v) => {
                    arr.push(v);
                });
                arr = [arr];
            } else {
                arr = skuPropertyTable;
            }
        }
        this.setState({ skuPropertyArray, skuPropertyTable: arr, skuType });
    };
    /**
     * @desc 获取sku价格返回值
     * */
    getNumResult = (numResult) => {
        this.setState({ numResult });
    };
    handleOk = () => {
        const { numResult } = this.state
        let stockArr = numResult.map(v => {
            return {
                productSkuId: v.SKUId,
                skuStock: v.stock
            }
        })
        this.updateStock(stockArr)
    }
    updateStock = async stockArr => {
        let res = await apiUpdateInventory([...stockArr])
        if (res.code === 0) {
            React.$message({
                type: 'info',
                content: '修改成功'
            })
            this.closeSkuDialog()
        }
    }
    //添加
    openDialog = (type) => {
        this.setState({ visible: true, title: '新增房号', type })
    }
    //编辑
    goEdit = (type, verificationPersonnelId, editorValue) => {
        this.setState({ visible: true, title: '修改房号', type, verificationPersonnelId, editorValue })
    }
    dialogCancel = () => {
        this.setState({ visible: false, title: '', type: '', verificationPersonnelId: '', editorValue: null });
    };
    //表格导出
    async toExportTable() {
        const { searchValue } = this.state
        this.setState({ down_loading: true })
        await React.$post('/management/productInfo/exportProductDetail', { ...searchValue, reviewStatus: 'T' }).then(res => {
            if (res.code === 0 && res.data.length >= 0) {
                let tH_data = [
                    { prop: 'productName', title: '商品名称' },
                    { prop: 'productId', title: '商品Id' },
                    { prop: 'sku', title: 'sku名称' },
                    { prop: 'materialId', title: '物料id' },
                    // { prop: 'price', title: '成本价' },
                    { prop: 'productSkuId', title: 'productSkuId' },
                    { prop: 'skuOriginalPrice', title: 'sku原价' },
                    { prop: 'skuCurrentPrice', title: 'sku现价' },
                    { prop: 'createTime', title: '商品创建时间' },
                    { prop: 'goodsStatus', title: '商品上下架' },
                    { prop: 'putawayTime', title: '上架时间' },
                    { prop: 'skuStatus', title: '规格上下架' },
                    { prop: 'skuStock', title: '库存' }
                ],
                    isSheet = true,
                    fileName = '商品列表',
                    tB_data = []
                res.data.forEach(item => {
                    tB_data.push({
                        productName: item.productName,
                        productId: item.productId,
                        sku: item.sku,
                        materialId: item.materialId,
                        // price: item.price ? (item.price / 100).toFixed(2) : '/',
                        productSkuId: item.productSkuId,
                        skuOriginalPrice: item.skuOriginalPrice,
                        skuCurrentPrice: item.skuCurrentPrice,
                        createTime: item.createTime,
                        goodsStatus: item.goodsStatus,
                        putawayTime: item.putawayTime,
                        skuStatus: item.skuStatus,
                        skuStock: item.skuStock,
                    })
                })
                this.setState({ down_loading: false })
                exportSheetTable({ fileName, tH_data, tB_data, isSheet })

            } else {
                React.$message({
                    type: 'warning',
                    content: '导出操作失败,请重试'
                })
                this.setState({ down_loading: false })
            }
        }).catch(err => {
            React.$message({
                type: 'warning',
                content: '导出操作失败,请重试'
            })
            this.setState({ down_loading: false })

        })
    }
    render() {
        const {
            columns,
            dataSource,
            pageData: { pageNo, pageSize },
            total,
            loading,
            visible,
            type,
            verificationPersonnelId,
            title
        } = this.state;
        return (
            <div className={"p-layout-box commodity-content"}>
                <SearchHeader openDialog={this.openDialog} getValue={this.getValue} toExport={() => this.toExportTable()} />
                <div className="p-layout-content-pagination">
                    <TheTable
                        scroll={{ x: "max-content", y: '63vh' }}
                        columns={columns}
                        dataSource={dataSource}
                        loading={loading}
                    />
                    <ThePagination
                        pageNo={pageNo}
                        pageSize={pageSize}
                        total={total}
                        pageChange={this.pageChange}
                    />
                </div>
                <TheDialog
                    title={title}
                    visible={visible}
                    handleCancel={this.dialogCancel}
                    footer={null}
                    width={400}
                >
                    <Add type={type} reload={this.getData} closeDialog={this.dialogCancel} verificationPersonnelId={verificationPersonnelId} />
                </TheDialog>
            </div>
        );
    }
}

export default List;
